//
//  AppDelegate.m
//  ENTBoostChat
//
//  Created by zhong zf on 14-8-2.
//  Copyright (c) 2014年 EB. All rights reserved.
//

#import "AppDelegate.h"
#import "BlockUtility.h"
#import "MainViewController.h"
#import "TalksTableViewController.h"
#import "RunningCache.h"
#import "CHKeychain.h"
#import <CoreData/CoreData.h>

//storyboard NAME
#define EBCHAT_STORYBOARD_NAME_LOGON @"Logon"
#define EBCHAT_STORYBOARD_NAME_MAIN @"Main"

//storyboard ID
#define EBCHAT_STORYBOARD_ID_LOGON_CONTROLLER @"logonController_ID"
#define EBCHAT_STORYBOARD_ID_SPLASH_SCREEN_CONTROLLER @"splashScreenController_ID"
#define EBCHAT_STORYBOARD_ID_TABBAR_CONTROLLER @"tabBarController_ID"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //如果是真机标准日志输出保存到文件
    UIDevice *device = [UIDevice currentDevice];
    NSLog(@"device model = %@", device.model);
    if ([device.model rangeOfString:@"Simulator"].location == NSNotFound) {
        [self redirectNSlogToFile];
    }
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    //设置服务地址(必须要在获取实例前调用才有效)
    [ENTBoostKit setServerAddress:@"entboost.entboost.com:18012"];
    
    //生成登录界面控制器
    UIStoryboard* logonStoryboard = [UIStoryboard storyboardWithName:EBCHAT_STORYBOARD_NAME_LOGON bundle:nil];
    self.logonViewController = [logonStoryboard instantiateViewControllerWithIdentifier:EBCHAT_STORYBOARD_ID_LOGON_CONTROLLER];
    self.splashScreenController = [logonStoryboard instantiateViewControllerWithIdentifier:EBCHAT_STORYBOARD_ID_SPLASH_SCREEN_CONTROLLER];

    //生成TabBarController实例
    self.tabBarController = [[UIStoryboard storyboardWithName:EBCHAT_STORYBOARD_NAME_MAIN bundle:nil] instantiateViewControllerWithIdentifier:EBCHAT_STORYBOARD_ID_TABBAR_CONTROLLER];
    
    self.window.rootViewController = self.splashScreenController;
    [self.window makeKeyAndVisible];
    
    //注册接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoffHandle:) name:EBCHAT_NOTIFICATION_MANUAL_LOGOFF object:nil]; //手工退出登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logonSuccessHandle:) name:EBCHAT_NOTIFICATION_MANUAL_LOGON_SUCCESS object:nil]; //手工登录成功
    
    //执行初始化恩布SDK环境
    [self initENTBoostKit];
    
    return YES;
}

- (void)dealloc
{
    //移除接收通知的注册
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EBCHAT_NOTIFICATION_MANUAL_LOGOFF object:nil]; //手工退出登录
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EBCHAT_NOTIFICATION_MANUAL_LOGON_SUCCESS object:nil]; //手工登录成功
}

//初始化环境
- (void)initENTBoostKit
{
    //测试应用ID可到恩布官网申请获取 www.entboost.com
    NSString* appId =@"278573612908";
    NSString* appKey =@"ec1b9c69094db40d9ada80d657e08cc6";
//    NSString* appId =@"6862743000169390";
//    NSString* appKey =@"4d92f11842472dfc46f3d79be264ca14";
    
    __block dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    __weak typeof(self)safeSelf = self; //安全引用self对象,防止Block循环引用
    [BlockUtility performBlockInGlobalQueue:^{
        //获取SDK接口全局单实例
        ENTBoostKit* ebKit = [ENTBoostKit sharedToolKit];
        
        //设置尝试自动登录
        NSNumber* autoLogon = [safeSelf dataForKey:EBCHAT_AUTO_LOGON_KEY];
        if (autoLogon) { //有结果
            if (autoLogon.boolValue) //允许自动登录
                ebKit.wantAutoLogon = YES;
            else //不允许自动登录
                ebKit.wantAutoLogon = NO;
        } else {
            [safeSelf saveData:@YES forKey:EBCHAT_AUTO_LOGON_KEY];
            ebKit.wantAutoLogon = YES;
        }
        
        //注册和初始化恩布SDK环境
        [ebKit registerWithAppId:appId appKey:appKey andDelegate:self onCompletion:^{
            NSLog(@"恩布SDK初始化成功");
            dispatch_semaphore_signal(sem);
            [BlockUtility performBlockInMainQueue:^{ //主线程中执行
                if (!ebKit.wantAutoLogon) {//非自动登录
                    self.window.rootViewController = self.logonViewController; //显示登录界面
                    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide]; //显示状态栏
                }
                
                safeSelf.logonViewController.loginButton.enabled = YES; //启用登录按钮
            }];
        } onFailure:^(NSError *error) {
            NSLog(@"恩布SDK初始化失败, code = %i, msg = %@", error.code, error.localizedDescription);
            dispatch_semaphore_signal(sem);
            [BlockUtility performBlockInMainQueue:^{ //主线程中执行
                //提示重新初始化
                NSString* msg = [NSString stringWithFormat:@"应用初始化失败(code = %i, msg = %@), 请重试", error.code, error.localizedDescription];
                UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:safeSelf cancelButtonTitle:@"重试" otherButtonTitles:nil, nil];
                [alertView show];
            }];
            
        }];
    }];
    dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 3.0f * NSEC_PER_SEC)); //最长等待3秒
}

//定义的委托, 提示初始化失败后再次执行初始化
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self initENTBoostKit];
}

//手工退出登录事件处理方法
- (void)logoffHandle:(NSNotification*)notif
{
    ENTBoostKit* ebKit = [ENTBoostKit sharedToolKit];
    
    //执行注销登录
    [ebKit asyncLogoff];
    //清空缓存
    [RunningCache clear];
    
    //因为是主动注销，所以设置禁止自动登录
    ebKit.wantAutoLogon = NO;
    [BlockUtility performBlockInMainQueue:^{
        //设置自动登录状态为否
        [self saveData:@NO forKey:EBCHAT_AUTO_LOGON_KEY];
        
        //删除记录的密码
        [CHKeychain removePassword];
        
        self.window.rootViewController = self.logonViewController; //显示登录界面
        self.logonViewController.loginButton.enabled = YES; //启用登录按钮
        self.logonViewController.passwordTextField.text = @""; //清空密码输入框
        
        self.tabBarController = nil;
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide]; //显示状态栏
    }];
}

//手工登录成功事件处理方法
- (void)logonSuccessHandle:(NSNotification*)notif
{
    __weak typeof(self) safeSelf = self;
    [BlockUtility performBlockInMainQueue:^{
        if (!safeSelf.tabBarController) {
            safeSelf.tabBarController = [[UIStoryboard storyboardWithName:EBCHAT_STORYBOARD_NAME_MAIN bundle:nil] instantiateViewControllerWithIdentifier:EBCHAT_STORYBOARD_ID_TABBAR_CONTROLLER];
        }
        safeSelf.window.rootViewController = safeSelf.tabBarController; //切换主界面
        [safeSelf.tabBarController setSelectedIndex:0]; //设置第一个tab为焦点
        
        //设置尝试自动登录
        [ENTBoostKit sharedToolKit].wantAutoLogon = YES;
        [safeSelf saveData:@YES forKey:EBCHAT_AUTO_LOGON_KEY];
    }];
    
}

#pragma mark - persistence

- (void)saveData:(id)data forKey:(NSString*)key
{
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject:data forKey:key];
    [defaults synchronize]; //用synchronize方法把数据持久化到standardUserDefaults数据库
}

- (id)dataForKey:(NSString*)key
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:key];
}

// 将NSlog打印信息保存到文件中
- (void)redirectNSlogToFile
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd-HHmmss"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *logFilePath = [NSString stringWithFormat:@"%@/entboost/logs/rollfile-%@.txt", paths[0], [dateFormatter stringFromDate:[NSDate date]]];
    
    NSString* dirPath = [logFilePath stringByDeletingLastPathComponent];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:dirPath]) {
        NSLog(@"try to create directory = %@", dirPath);
        NSError* pError;
        [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&pError];
        if(pError) {
            NSLog(@"create directory = %@ error, code = %li, msg = %@", dirPath, (long)pError.code, pError.localizedDescription);
        }
    }
    
//    // 先删除已经存在的文件
//    NSFileManager *defaultManager = [NSFileManager defaultManager];
//    [defaultManager removeItemAtPath:logFilePath error:nil];
    
    // 将log输入到文件
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
}


#pragma mark - application event
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    //更新应用图标上数字
    application.applicationIconBadgeNumber = 0;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - ENTBoostKitDelegate
- (void)onRecevieMessage:(EBMessage*)message
{
    [self.tabBarController.talksController dispatchReceviedMessage:message];
}

- (void)onCallConnected:(const EBCallInfo *)callInfo
{
    [self.tabBarController.talksController handleCall:callInfo callActionType:CALL_ACTION_TYPE_CONNECTED];
}

- (void)onCallBusy:(const EBCallInfo *)callInfo
{
    [self.tabBarController.talksController handleCall:callInfo callActionType:CALL_ACTION_TYPE_BUSY];
}

- (void)onCallReject:(const EBCallInfo *)callInfo
{
    [self.tabBarController.talksController handleCall:callInfo callActionType:CALL_ACTION_TYPE_REJECT];
}

- (void)onCallHangup:(const EBCallInfo *)callInfo
{
    [self.tabBarController.talksController handleCallHangup:callInfo];
}

- (void)onCallAlerting:(const EBCallInfo *)callInfo toUid:(uint64_t)toUid
{
    [self.tabBarController.talksController handleCallAlerting:callInfo toUid:toUid];
}

- (void)onCallIncoming:(const EBCallInfo *)callInfo fromUid:(uint64_t)fromUid fromAccount:(NSString *)fromAccount vCard:(EBVCard *)vCard clientAddress:(NSString *)clientAddress
{
    [self.tabBarController.talksController handleCallIncoming:callInfo fromUid:fromUid fromAccount:fromAccount vCard:vCard clientAddress:clientAddress];
}

- (void)onAutoLogonEvent:(BOOL)state accountInfo:(EBAccountInfo *)accountInfo error:(NSError *)error
{
    __weak typeof(self) safeSelf = self;
    [BlockUtility performBlockInMainQueue:^{
        if (state) {
            //把MainViewController设置为根控制器
            safeSelf.window.rootViewController = safeSelf.tabBarController;
        } else {
            //把LogonViewController设置为根控制器
            safeSelf.window.rootViewController = safeSelf.logonViewController;
            safeSelf.logonViewController.loginButton.enabled = YES;
        }
    }];
}

- (void)onLoadedEmotionsComplete:(NSArray *)expressions headPhotos:(NSArray *)headPhotos
{
    [self.tabBarController.talksController refreshEmotions:expressions headPhotos:headPhotos];
}

@end
